package com.maduar.demo.thread;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @date 2021-05-06 22:10
 */
public class SynchronizeDemo {

    private static Lock lock = new ReentrantLock();
    private static int i = 0;

    public static synchronized void lock1() {
        System.out.println("lock1");
        lock2();
    }

    public static synchronized void lock2() {
        System.out.println("lock2");
    }

    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                lock1();
            }
        }.start();

        try {
            lock.lock();
            lock.lock();
            System.out.println(i++);
        } finally {
            lock.unlock();
            lock.unlock();
        }

        Thread t1 = new Thread("thread1"){
            @SneakyThrows
            @Override
            public void run() {
                try {
                    if (lock.tryLock(5, TimeUnit.SECONDS)) {
                        TimeUnit.SECONDS.sleep(6);
                    } else {
                        System.out.println(Thread.currentThread().getName() + "获取锁失败");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };
        Thread t2 = new Thread("thread2"){
            @SneakyThrows
            @Override
            public void run() {
                try {
                    if (lock.tryLock(5, TimeUnit.SECONDS)) {
                        TimeUnit.SECONDS.sleep(6);
                    } else {
                        System.out.println(Thread.currentThread().getName() + "获取锁失败");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };

        new Thread(){
            @Override
            public void run() {
                System.out.println(Singleton2.getInstance());
            }
        }.start();

        t1.start();
        t2.start();
    }

}
